#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QFileDialog>
#include <QFile>
#include <QDebug>
#include <QTextEdit>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMenuBar* menuBar = new QMenuBar(this);
    this->setMenuBar(menuBar);

    QMenu* fileMenu = new QMenu("文件");
    menuBar->addMenu(fileMenu);

    QAction* openAction = new QAction("打开");
    QAction* saveAction = new QAction("保存");
    fileMenu->addAction(openAction);
    fileMenu->addAction(saveAction);

    QTextEdit* textEdit = ui->textEdit;
    textEdit->setPlaceholderText("请在这里输入内容");

    connect(openAction,&QAction::triggered,this,&MainWindow::openFileByDialog);
    connect(saveAction,&QAction::triggered,this,&MainWindow::saveFileByDialog);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openFileByDialog()
{
    //通过QFileDialog获取文件
    QString filePath = QFileDialog::getOpenFileName();
    //通过路径，实例化文件对象
    QFile file(filePath);
    if(file.open(QIODevice::ReadOnly))
    {
        QByteArray textArray = file.readAll();
        QString textStr = QString::fromUtf8(textArray);
        ui->textEdit->setText(textStr);
    }
    else
    {
        qDebug() << "文件：" << filePath << " 打开失败";
    }
}

void MainWindow::saveFileByDialog()
{
    QString filePath = QFileDialog::getSaveFileName();
    qDebug() << filePath;
    QFile file(filePath);
    if(file.open(QIODevice::WriteOnly))
    {
        QString textStr = ui->textEdit->toPlainText();
        QByteArray textArray = textStr.toUtf8();
        file.write(textArray);
    }
    else
    {
        qDebug() << "文件：" << filePath << " 打开失败";
    }
}

void MainWindow::resizeEvent(QResizeEvent* ev)
{
    ui->textEdit->setGeometry(0,0,ev->size().width(),ev->size().height());
}

